<script setup lang="ts">
/**
 * @desc GatewayNode
 * @author MiyueFE <https://github.com/miyuesc>
 * @since 2024/7/12 上午10:06
 */

import { type PropType, computed } from 'vue'
import type { BaseNode, BranchNodeList, FlowDirection, GatewayNode } from '@/types'
import { createNode, setNodeInMap } from '@/utils/element-utils'
import { checkParallelGateway } from '@/configuration/check-node-types'

defineOptions({ name: 'GatewayNode' })

const $props = defineProps({
  data: {
    type: Object as PropType<GatewayNode>,
    required: true,
  },
  direction: {
    type: String as PropType<FlowDirection>,
    default: 'vertical',
    validator: (v: FlowDirection) => ['vertical', 'horizontal'].includes(v),
  },
})
const doEmit = defineEmits(['update:data'])

const computedGatewayNode = computed<GatewayNode>({
  get: () => $props.data,
  set: node => doEmit('update:data', node),
})

const isParallelGatewayChild = computed(() => checkParallelGateway($props.data))

function nextNodeTraversal(node?: BaseNode): BaseNode[] {
  if (!node) {
    return []
  }
  const list: BaseNode[] = []
  let curNode: BaseNode | undefined = node
  while (curNode) {
    list.push(curNode)
    curNode = curNode.$next
  }
  return list
}
const branchesNodeList = computed<BranchNodeList[]>(() => {
  const branches: BranchNodeList[] = []
  const expressions = computedGatewayNode.value.$expressions
  for (const ex of expressions) {
    branches.push({
      expression: ex,
      nextNodeList: nextNodeTraversal(ex.$next),
    })
  }
  return branches
})

function addExpression() {
  const prefix = isParallelGatewayChild.value ? '分支' : '条件'
  const newExpression = createNode('expression', computedGatewayNode.value, `${prefix}-${computedGatewayNode.value.$expressions.length + 1}`)
  setNodeInMap(newExpression)
  computedGatewayNode.value.$expressions.push(newExpression)
}
</script>

<template>
  <div class="flow-node flow-gateway">
    <div class="gateway-node__behavior">
      <a-button type="primary" round @click="addExpression">
        {{ isParallelGatewayChild ? '添加分支' : '添加条件' }}
      </a-button>
    </div>

    <div class="gateway-node__branches">
      <div
        v-for="(branch, bi) in branchesNodeList"
        :key="branch.expression.id"
        class="branch-col"
      >
        <div class="branch-col_prefix" />
        <div class="branch-col_content">
          <DingFlowList
            v-model:data="branchesNodeList[bi].expression"
            :idx="bi"
            :direction="direction"
          />
        </div>
        <div class="branch-col_suffix" />
      </div>
    </div>
  </div>
</template>
